import {Router, RouteRecordRaw} from 'vue-router'
import {arrCopyDeep} from 'st-common-core'
import {useMenuStore, MenuObjPropNameEnum, MenuTypeEnum} from '@menu'
import {RouteNameConst} from '@config'

/**
 * 动态添加路由
 *
 * @param {Router} router 路由实例
 */
export const addRoutesDynamic = async (router: Router) => {
  // 请求获取菜单数据
  const menuStore = useMenuStore()
  await menuStore.getMenuDataByReq()
  // 动态添加路由
  const routes = arrCopyDeep({
    origin: menuStore.getMenuOptions(),
    props: [
      MenuObjPropNameEnum.PAGE_PATH,
      MenuObjPropNameEnum.ROUTE_NAME,
      MenuObjPropNameEnum.ROUTE_PATH,
      MenuObjPropNameEnum.CHILDREN,
    ],
    propsMap: {
      [MenuObjPropNameEnum.ROUTE_NAME]: 'name',
      [MenuObjPropNameEnum.ROUTE_PATH]: 'path',
      [MenuObjPropNameEnum.PAGE_PATH]: 'component',
    },
    targetPropValMap: {
      component: (origin) => {
        if (!origin[MenuObjPropNameEnum.PAGE_PATH]) return null
        return () => import(origin[MenuObjPropNameEnum.PAGE_PATH])
      }
    },
    excludeArrItem: (item) => item[MenuObjPropNameEnum.TYPE] === MenuTypeEnum.LINK,
  }) as RouteRecordRaw[]
  routes.forEach((route) => {
    router.addRoute(RouteNameConst.index.en, route)
  })
}
